/*
 * File:    Interrupts.c
 * Project:	HobbyPilotFirmware (HPF)
 * Author:  Wouter van Verre
 *
 * Created on February 8, 2011, 10:30 PM
 */

#include "Header.h"

void initInterrupts(void)
{
    // Set the interrupt priorities
    IPC1bits.T2IP 		= 7;		// Set Timer2 to be priority level 7
	IPC5bits.T4IP 		= 6;		// Set Timer1 to be priority level 5    
    IPC0bits.T1IP 		= 5;		// Set Timer1 to be priority level 5    
	IPC6bits.U2RXIP 	= 4;		// Set the UART2 module receive interrupt priority to 5	
    IPC2bits.U1RXIP 	= 4;		// Set the UART1 module receive interrupt priority to 4
	IPC2bits.ADIP 		= 4; 		// Set the priority of the AD interrupt
	IPC2bits.U1TXIP 	= 3;		// Set the UART1 module transmission interrupt priority to 3
    IPC6bits.U2TXIP 	= 3;		// Set the UART2 module transmission interrupt priority to 3

    // Enable the interrupts    
	IEC0bits.T2IE 		= 1;		// Enable the Timer2 interrupt
    IEC0bits.T1IE 		= 1;		// Enable the Timer1 interrupt    
	IEC1bits.T4IE 		= 1;		// Enable the Timer1 interrupt
    IEC0bits.U1TXIE 	= 1;		// Enable the UART1 module transmission interrupt
    IEC0bits.U1RXIE 	= 1;		// Enable the UART1 module receive interrupt
	IEC1bits.U2TXIE 	= 1;		// Enable the UART2 module transmission interrupt
    IEC1bits.U2RXIE 	= 1;		// Enable the UART2 module receive interrupt
	IEC0bits.ADIE 		= 1;		// Enable the the AD interrupt


    // Clear the interrupt flags
    IFS0bits.T2IF 		= 0;		// Clear the Timer2 interrupt flag
 	IFS1bits.T4IF 		= 0;		// Clear the Timer1 interrupt flag
 	IFS0bits.T1IF 		= 0;		// Clear the Timer1 interrupt flag
    IFS0bits.U1TXIF 	= 0;		// Clear the UART1 module transmission interrupt flag
    IFS0bits.U1RXIF 	= 0;		// Clear the UART1 module recieve interrupt flag
    IFS1bits.U2TXIF 	= 0;		// Clear the UART2 module transmission interrupt flag
    IFS1bits.U2RXIF		= 0;		// Clear the UART2 module recieve interrupt flag
	IFS0bits.ADIF 		= 0; 		// Clear the AD interrupt flag
}

void EnterInterrupt(void)
{
	T4CONbits.TON = 1;

	cpuStackUse = WREG15;
	cpuStackUseMax = (cpuStackUse > cpuStackUseMax) ? cpuStackUse : cpuStackUseMax;
}
